package com.bigluo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bigluo.api.BaseResponse;
import com.bigluo.api.rsp.QryUsrInfoRsp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;

/**
 * Created by luojun on 2017/9/4.
 */
public class CustomHttpMessageConverter implements HttpMessageConverter {
    private Logger logger = LoggerFactory.getLogger(CustomHttpMessageConverter.class);
    private static List<MediaType> mediaTypeList = Arrays.asList(MediaType.APPLICATION_JSON);
    public SerializerFeature [] serializerFeature = new SerializerFeature[0];
    public boolean canRead(Class aClass, MediaType mediaType) {
        logger.info("自定义转换器 请求mediatype:{}",mediaType);
        if(mediaType == null) return true;
        for(MediaType source : mediaTypeList) {
            if(source.includes(mediaType)) {
                return true;
            }
        }
        return false;
    }

    public boolean canWrite(Class aClass, MediaType mediaType) {
        if(mediaType == null )return true;
        for(MediaType source : mediaTypeList) {
            if(source.includes(mediaType)) {
                return true;
            }
        }
        return false;
    }

    public Object read(Class aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return null;
    }

    public void write(Object o, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {
        //统一处理version
        if(o instanceof BaseResponse) {
            ((BaseResponse) o).setVersion("1.0");
        }
        OutputStream outputStream = httpOutputMessage.getBody();
        String text = JSON.toJSONString(o,serializerFeature);
        logger.info("调用HTTP接口返回值：{}",JSON.toJSONString(o));
        outputStream.write(text.getBytes("utf-8"));
    }

    public List<MediaType> getSupportedMediaTypes() {
        return mediaTypeList;
    }

    public SerializerFeature[] getSerializerFeature() {
        return serializerFeature;
    }

    public void setSerializerFeature(SerializerFeature[] serializerFeature) {
        this.serializerFeature = serializerFeature;
    }
}
